<?php
abstract class jfAsyncLoader {
   
  abstract protected function setIncluded();
  abstract protected function getSourceFilesForPosition($position);
  
  abstract 	protected function supportsCallbacks();

  public function getHtmlToLoadSources() {
  	
  	$html = '';

    $positions = sfContext::getInstance()->getResponse()->getPositions();

    $html.= '<script>(function($) {'; 

    foreach($positions as $index => $position) {
    
      $sourceFilesForPosition = $this->getSourceFilesForPosition($position);
      if (empty($sourceFilesForPosition)) {
        $html.= 'function load'.$index.'() {';
          if ($index < count($positions)-1) {
        		$html.= 'load'.($index+1).'();';
        	}
        $html.= '}';
      }
      else {
        $jsonLoadConfigurations = array();
        foreach($sourceFilesForPosition as $file => $options) {
          $jsonLoadConfigurations[] = $this->getJsonLoadConfigForSourceFile($file, $options);
        }
    
        $html.= 'function load'.$index.'() {
          $.rloader(['.implode($jsonLoadConfigurations, ', ');
          if ($index < count($positions)-1) {
          	if ($this->supportsCallbacks()) {
          		$html.= ', { event: "onready", func: load'.($index+1).' }';
          	}
          }
          $html.= ']);
        }';
      }
      
    }
    
    $html.= 'load0();';
    if (!$this->supportsCallbacks()) {
    	$html.= 'load1();';
    	$html.= 'load2();';
    }
    
    $html.= '})(jQuery);</script>';

    $this->setIncluded();
    
    return $html;
  }

  public function initialize($pathToJQuery) {
  	$filename = 'rloader1.5.3_'.(sfConfig::get('sf_environment') === 'dev' ? 'fin' : 'min').'.js';
  
  	$html = '<script src="'.$pathToJQuery.'"></script>';
  	$html.= '<script src="/jfAsyncLoaderPlugin/vendor/rloader/'.$filename.'"></script>';
  
  	return $html;
  }
  
  private function getJsonLoadConfigForSourceFile($file, $options) {
  
  	if (is_numeric($file) && is_string($options)) {
  		$file = $options;
  		$options = array();
  	}
  
  	$json = "{src: '$file'}";
  
  	return $json;
  }

}
